﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using GranitePackageSystem.GranitePackagingService;
using GranitePackageSystem.Views.ChildWindows;

namespace GranitePackageSystem.Views.Request
{
    public partial class RequestSummary : Page
    {
        private bool softwareContracted;
        private LicensingData licData;
        private GranitePackagingService.Request currentRequest = new GranitePackagingService.Request();
        private Package packageData;
        private Program programData;
        private ObservableCollection<WorkLogEntry> workLog;
        public RequestSummary()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            checkRoles();

            if (App.Current.Resources.Contains("Current Request"))
            {
                currentRequest = App.Current.Resources["Current Request"] as GranitePackagingService.Request;

                updateRequestNavTable();

                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Loading Request Licensing Data";

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getPackageListCompleted += new EventHandler<getPackageListCompletedEventArgs>(proxy_getPackageListCompleted_INIT);
                proxy.getPackageListAsync(currentRequest);
            }
            else
            {
                this.NavigationService.Navigate(new System.Uri("/Home", System.UriKind.Relative));
            }
        }
        private void updateRequestNavTable()
        {
            DateTime MIN_SQL_DATE = (DateTime)App.Current.Resources["Min SQL Date"];
            if (App.Current.Resources.Contains("Current Request"))
            {
                expanderRequest.Visibility = System.Windows.Visibility.Visible;
                if (currentRequest.Stage.Equals("Staging"))
                {
                    linkTestingDetails.Visibility = System.Windows.Visibility.Visible;
                    if (currentRequest.VirtStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                    {
                        linkPackageDetails.Visibility = System.Windows.Visibility.Visible;
                        if (currentRequest.PackageStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                        {
                            linkLicensingDetails.Visibility = System.Windows.Visibility.Visible;
                            if (currentRequest.LicensingStepComplete.CompareTo(MIN_SQL_DATE) > 0)
                            {
                                linkSummaryDetails.Visibility = System.Windows.Visibility.Visible;
                            }
                            else
                            {
                                linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                            }
                        }
                        else
                        {
                            linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                            linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                        }
                    }
                    else
                    {
                        linkPackageDetails.Visibility = System.Windows.Visibility.Collapsed;
                        linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                        linkSummaryDetails.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                else
                {
                    btnSubmitRequest.Visibility = System.Windows.Visibility.Collapsed;
                    linkLicensingDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkPackageDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkTestingDetails.Visibility = System.Windows.Visibility.Collapsed;
                    linkSummaryDetails.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }
        void proxy_getLicensingDataCompleted_INIT(object sender, getLicensingDataCompletedEventArgs e)
        {
            licData = e.Result;

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.getAllDivisionsCompleted += new EventHandler<getAllDivisionsCompletedEventArgs>(proxy_getAllDivisionsCompleted_INIT);
            proxy.getAllDivisionsAsync();
        }

        void proxy_getAllDivisionsCompleted_INIT(object sender, getAllDivisionsCompletedEventArgs e)
        {
            boxDivisonOfOwnership.ItemsSource = e.Result;
            if (e.Result.Count > 0)
            {
                boxDivisonOfOwnership.SelectedIndex = 0;
            }

            // If No existing Licensing Data
            if (licData.LicensingID == null)
            {
                this.NavigationService.Navigate(new System.Uri("/Request/Licensing", System.UriKind.Relative));
            }
            // Existing Licensing Data for Request
            else
            {
                updateLicensingInputs(licData);
                lockLicensingInputs();
                busyIndicatorMain.BusyContent = "Getting Request Work Log Data";

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getRequestWorkLogCompleted += new EventHandler<getRequestWorkLogCompletedEventArgs>(proxy_getRequestWorkLogCompleted_INIT);
                proxy.getRequestWorkLogAsync(currentRequest);
                
            }
        }

        void proxy_getPackageListCompleted_INIT(object sender, getPackageListCompletedEventArgs e)
        {
            //Valid amount of Packages Per Request
            if (e.Result.Count == 1)
            {
                packageData = e.Result[0];
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getProgramListCompleted += new EventHandler<getProgramListCompletedEventArgs>(proxy_getProgramListCompleted_INIT);
                proxy.getProgramListAsync(packageData);
                panelPackageInfoDetails.DataContext = packageData;
            }
            else
            {
                MessageBox.Show("Invalid Number of packages for this request");
                this.NavigationService.Navigate(new Uri("/Home", System.UriKind.Relative));
            }
        }

        void proxy_getProgramListCompleted_INIT(object sender, getProgramListCompletedEventArgs e)
        {
            //Valid number of Programs
            if (e.Result.Count == 1)
            {
                programData = e.Result[0];

                panelProgramInfoDetails.DataContext = programData;
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getLicensingDataCompleted += new EventHandler<getLicensingDataCompletedEventArgs>(proxy_getLicensingDataCompleted_INIT);
                proxy.getLicensingDataAsync(currentRequest);
            }
            else
            {
                MessageBox.Show("Invalid Number of programs for this request");
                this.NavigationService.Navigate(new Uri("/Home", System.UriKind.Relative));
            }
        }
        
        void proxy_getRequestWorkLogCompleted_INIT(object sender, getRequestWorkLogCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            workLog = new ObservableCollection<WorkLogEntry>();
            if (e.Result.Count > 0)
            {
                foreach (WorkLogEntry entry in e.Result)
                {
                    WorkLogEntry modifiedEntry = entry;
                    modifiedEntry.NoteDate = modifiedEntry.NoteDate.ToLocalTime();

                    workLog.Add(modifiedEntry);
                }
            }
            gridWorkLog.ItemsSource = workLog;
        }

        private void checkRoles()
        {
            Web.User user = WebContext.Current.User;
            bool userInARole = false;

            if (user.IsInRole("GENMILLS\\GPS_Requesters")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_Administrators")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_LicensingApprovers")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_DeploymentApprovers")) { userInARole = true; }

            if (userInARole) { }
            else { this.NavigationService.Navigate(new System.Uri("/Unauthorized", System.UriKind.Relative)); }
        }
        private void boxDivisonOfOwnership_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (((Division)boxDivisonOfOwnership.SelectedItem).Departments.Count > 0)
                {
                    panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Visible;
                    boxDepartmentOfOwnership.SelectedIndex = 0;
                }
                else
                {
                    panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            catch { }
        }
        private void updateSoftwareContracted(bool status)
        {
            softwareContracted = status;
            if (status == true)
            {
                btnSoftwareContracted_YES.Background = new SolidColorBrush(new Color() { A = 255, B = 242, G = 188, R = 149 });
                btnSoftwareContracted_NO.Background = new SolidColorBrush();
                panelSoftwareEULA.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                btnSoftwareContracted_YES.Background = new SolidColorBrush();
                btnSoftwareContracted_NO.Background = new SolidColorBrush(new Color() { A = 255, B = 242, G = 188, R = 149 });
                panelSoftwareEULA.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void lockLicensingInputs()
        {
            boxDepartmentOfOwnership.IsEnabled = false;
            boxDivisonOfOwnership.IsEnabled = false;
            boxLicenseKeyChoice.IsEnabled = false;
            boxPONumber.IsEnabled = false;
            boxSoftwareCost.IsEnabled = false;
            boxSoftwareEULA.IsEnabled = false;
            boxSoftwareOrigin.IsEnabled = false;
            boxSoftwareProcurementMethod.IsEnabled = false;
            listBoxLicenseKeys.IsEnabled = false;
        }
        private void updateLicensingInputs(LicensingData licData)
        {
            foreach (ComboBoxItem item in boxSoftwareOrigin.Items)
            {
                if (item.Content.Equals(licData.SoftwareOrigin))
                {
                    boxSoftwareOrigin.SelectedItem = item;
                    break;
                }
            }
            switch (licData.SoftwareOrigin)
            {
                case "Not General Mills Developed":
                     switch (licData.ProcurementMethod.ToUpper())
                    {
                        case "SAP SRM REQUEST":
                            boxSoftwareProcurementMethod.SelectedIndex = 0;
                            boxPONumber.Text = licData.PO_Number;
                            break;
                        case "MAXIMO REQUEST":
                            boxSoftwareProcurementMethod.SelectedIndex = 1;
                            boxPONumber.Text = licData.PO_Number;
                            break;
                        case "CORPORATE CREDIT CARD":
                            boxSoftwareProcurementMethod.SelectedIndex = 2;                            
                            break;
                        case "PERSONAL CREDIT CARD":
                            boxSoftwareProcurementMethod.SelectedIndex = 3;
                            break;
                        case "NO COST":
                            boxSoftwareProcurementMethod.SelectedIndex = 4;
                            panelSoftwareCost.Visibility = System.Windows.Visibility.Collapsed;
                            panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                            break;
                        case "IS Sourcing PCard":
                            break;
                        default:
                            break;
                    }

                    switch (licData.SoftwareCost)
                    {
                        case "0-$1,000":
                            boxSoftwareCost.SelectedIndex = 0;
                            break;
                        case "1,000-$10,000":
                            boxSoftwareCost.SelectedIndex = 1;
                            break;
                        case "$10,000+":
                            boxSoftwareCost.SelectedIndex = 2;
                            break;
                        default:
                            break;
                    }

                    softwareContracted = licData.SoftwareContracted;
                    updateSoftwareContracted(softwareContracted);

                    if (!licData.SoftwareContracted)
                    {
                        boxSoftwareEULA.Selection.Text = licData.SoftwareEULA;
                    }
                    if (licData.LicenseKeys.Count != 0)
                    {
                        if (licData.LicenseKeys.Count > 1)
                        {
                            boxLicenseKeyChoice.SelectedIndex = 1;
                        }
                        else
                        {
                            boxLicenseKeyChoice.SelectedIndex = 0;
                        }
                        foreach (LicenseKey licKey in licData.LicenseKeys)
                        {
                            listBoxLicenseKeys.Items.Add(licKey.Key.ToString());
                        }
                    }
                    else
                    {
                        boxLicenseKeyChoice.SelectedIndex = 2;
                    }
                    break;
                case "General Mills Developed":
                    panelSubSoftwareOrigin.Visibility = System.Windows.Visibility.Collapsed;
                    break;
            }

            foreach (Division division in boxDivisonOfOwnership.Items)
            {
                if (division.Name.Equals(licData.DivisionOfOwnership))
                {
                    boxDivisonOfOwnership.SelectedIndex = boxDivisonOfOwnership.Items.IndexOf(division);
                    break;
                }
            }
            if (!licData.DepartmentOfOwnership.Equals(string.Empty))
            {
                foreach (Department department in boxDepartmentOfOwnership.Items)
                {
                    if (department.name.Equals(licData.DepartmentOfOwnership))
                    {
                        boxDepartmentOfOwnership.SelectedIndex = boxDepartmentOfOwnership.Items.IndexOf(department);
                        break;
                    }
                }
            }
            else { panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Collapsed; }
        }

        private void btnSubmitRequest_Click(object sender, RoutedEventArgs e)
        {
            currentRequest.Status = "Summary Complete";

            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            busyIndicatorMain.IsBusy = true;
            busyIndicatorMain.BusyContent = "Submitting Request";

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted);
            proxy.saveRequestAsync(currentRequest);
        }

        void proxy_saveRequestCompleted(object sender, saveRequestCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();

            proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted);
            proxy.getRequestAsync(currentRequest.requestID,0);
        }

        void proxy_getRequestCompleted(object sender, getRequestCompletedEventArgs e)
        {
            currentRequest = e.Result;

            Application.Current.Resources.Remove("Current Request");
            Application.Current.Resources.Add("Current Request", currentRequest);

            if (currentRequest.Stage.Equals("Licensing"))
            {
                busyIndicatorMain.IsBusy = false;
                this.NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
            }
            else
            {
                busyIndicatorMain.BusyContent = currentRequest.Status;

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();

                proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted);
                proxy.getRequestAsync(currentRequest.requestID, 10);
            }
        }
        private void gridWorkLog_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WorkLogEntry entry = (WorkLogEntry)gridWorkLog.SelectedItem;
            if (entry != null)
            {
                WorkLogEntryDetails childWindow = new WorkLogEntryDetails(entry);
                childWindow.boxWorkLogNotes.IsReadOnly = true;
                childWindow.Show();
            }
        }
        private void btnAddWorklogEntry_Click(object sender, RoutedEventArgs e)
        {
            Web.User user = WebContext.Current.User;

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.getUserFriendlyNameCompleted += new EventHandler<getUserFriendlyNameCompletedEventArgs>(proxy_getUserFriendlyNameCompleted_AddWorkLogEntry);
            proxy.getUserFriendlyNameAsync(user.Name.Split('\\')[1].ToString(), user.Name.Split('\\')[0].ToString());
            busyIndicatorMain.BusyContent = "Creating New Work Log Entry";
            busyIndicatorMain.IsBusy = true;
        }

        void proxy_getUserFriendlyNameCompleted_AddWorkLogEntry(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            WorkLogEntry entry = new WorkLogEntry()
            {
                Note = String.Empty,
                NoteDate = DateTime.UtcNow,
                RequestID = currentRequest.requestID,
                UserName = e.Result.ToString(),
                WorkLogID = System.Guid.NewGuid().ToString()
            };

            WorkLogEntryDetails childWindow = new WorkLogEntryDetails(entry);
            childWindow.Closed += new EventHandler(childWindow_Closed_WorkLogEntry);

            childWindow.Show();
        }

        void childWindow_Closed_WorkLogEntry(object sender, EventArgs e)
        {
            WorkLogEntryDetails childWindow = (WorkLogEntryDetails)sender;
            if (childWindow.DialogResult.Value == true)
            {
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Saving Work Log Entry";
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.createWorkLogEntryCompleted += new EventHandler<createWorkLogEntryCompletedEventArgs>(proxy_createWorkLogEntryCompleted);
                proxy.createWorkLogEntryAsync(childWindow.entry.UserName, childWindow.entry.RequestID, childWindow.entry.Note, childWindow.entry.NoteDate);
            }
        }

        void proxy_createWorkLogEntryCompleted(object sender, createWorkLogEntryCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            WorkLogEntry modifiedWorkLogEntry = e.Result;
            modifiedWorkLogEntry.NoteDate = modifiedWorkLogEntry.NoteDate.ToLocalTime();
            workLog.Add(modifiedWorkLogEntry);
        }
    }
}
